import $ from "jquery";
import { ElLoading, ElMessage } from "element-plus";
// 加载动画
let loadding = null as any;
const eleLoadding = (text?: string) => {
  if (text == "" || text == undefined) {
    text = "Loading...";
  }
  return ElLoading.service({
    lock: true,
    text: text,
    spinner: "el-icon-loading",
    target: "#container",
    background: "rgba(0,0,0,0.7)"
  });
};
const ajaxDefault = {
  beforeSend: function (xhr: any) {
    loadding = eleLoadding();
  },
  complete: (xhr: any) => {},
  data: {},
  dataType: null,
  success: (data: any, textStatus: string, jqXHR: any) => {
    if (data == undefined) {
      ElMessage({
        message: "返回结果异常",
        type: "warning"
      });
    } else if (data.code == 200) {
      let msg = ("调用成功，返回状态码为：" + data.code) as any;
      if (msg.code != 200) {
        msg += "；返回信息为:" + data.message;
      }
    }
  },
  error: (xhr: any, error: any, exception: any) => {
    ElMessage({
      message: "调用错误",
      type: "error"
    });
  }
};
function fnBeforeSend(xhr: any, callback: Function) {
  (callback || ajaxDefault.beforeSend)(xhr);
}
function fnAjaxSuccess(data: any, textStatus: any, jqXHR: any, callback: Function) {
  (callback || ajaxDefault.complete)(data, textStatus, jqXHR);
}
function fnComplete(data: any, textStatus: any, callback?: Function) {
  loadding.close();
  (callback || ajaxDefault.complete)(data, textStatus);
}
export class utils {
  post = (obj: any) => {
    const paramObj = { ...obj } as any;
    const finalData = { ...paramObj.data } as any;
    $.ajax({
      type: "POST",
      url: paramObj.url,
      data: finalData,
      beforeSend: function (xhr: any) {
        fnBeforeSend(xhr, paramObj.beforeSend);
      },
      complete: function (xhr: any, textStatus: any) {
        fnComplete(xhr, textStatus, paramObj.complete);
      },
      success: function (data: any, textStatus: any, jqXHR: any) {
        fnAjaxSuccess(data, textStatus, jqXHR, paramObj.success);
      }
    });
  };
  get(obj: any) {
    const paramObj = { ...obj } as any;
    const finalData = { ...paramObj.data } as any;
    $.ajax({
      type: "GET",
      url: paramObj.url,
      data: finalData,
      beforeSend: function (xhr: any) {
        fnBeforeSend(xhr, paramObj.beforeSend);
      },
      complete: function (xhr: any, textStatus: any) {
        fnComplete(xhr, paramObj.complete);
      },
      dataType: paramObj.dataType || ajaxDefault.dataType,
      success: function (data: any, textStatus: any, jqXHR: any) {
        fnAjaxSuccess(data, textStatus, jqXHR, paramObj.success);
      }
    });
  }
}
